import json
import traceback

from baseclass.send_email import SendMail
from util.data2html import data2html
# from task.CrawlHouse import CrawlHouse
from decimal import Decimal

class HouseNotify:

    def __init__(self):
        self.mail = SendMail()
        # self.crawl = CrawlHouse()

    '''
      house_change变化对象
    '''
    def notify_house_change(self,house_change):
        '''
        邮件，微信，或者网站通知.
        '''
        text = "房价发生变化，请查看。house_id：{0}.name:{3},之前价格：{1}. 现在价格:{2}".format(house_change.house.house_id,house_change.price,house_change.house.price,house_change.house.name)
        title = "房源变化通知。id：{0}".format(house_change.house.house_id)
        print("房价发生变化，请查看。信息：{0}".format(house_change))
        try:
            self.mail = SendMail()
            self.mail.send_email(title, msghtml=text)
        except Exception as e:
            print("通知房源变更出现异常.{0}.e:{1}".format(title,e))

    def notify_change_house_list(self,house_change_list):
        title = "关注房源价格变化汇总通知.变化个数-{0}.".format(len(house_change_list))
        data_list = []
        for item in house_change_list:
            new_i = {}
            new_i["house_id"] = item.house.house_id
            new_i["name"] = item.house.name
            new_i["size"] = item.house.size
            new_i["pre_price"] = item.price
            new_i["cur_price"] = item.house.price
            new_i["diff"] = round(Decimal(item.house.price) - Decimal(item.price), 0)
            data_list.append(new_i)
        data_list.sort(key=lambda x:x["diff"])
        change_list = data2html(data_list, 'house_change.tpl')
        self.mail = SendMail()
        self.mail.send_email(subject=title,msghtml=change_list)

    '''
    通知小区售房数量和均价有变动
    '''
    def notify_xiaoqu_change(self,xiaoqu_change):
        title = "通知小区变化"
        try:
            text = "小区房源发生变化，请查看。xiaoqu_id：{0}.name:{1}。之前数量：{2}。现在数量：{3}".format(
                xiaoqu_change.cur_xiaoqu.xiaoqu_id, xiaoqu_change.cur_xiaoqu.name,xiaoqu_change.pre_xiaoqu.get("online_house_num"),xiaoqu_change.cur_xiaoqu.on_sale)
            title = "小区房源发生变化。id：{0}".format(xiaoqu_change.cur_xiaoqu.xiaoqu_id)
            print("小区发生变化，请查看。信息：{0}".format(xiaoqu_change))
            self.mail = SendMail()
            self.mail.send_email(title, msghtml=text)
            #爬取该小区房源
            # self.crawl.crawl_house_by_xiaoqu(id_list=[xiaoqu_change.cur_xiaoqu.xiaoqu_id])
        except Exception as e:
            print("通知房源变更出现异常.{0}.e:{1}".format(title,traceback.print_exc()))



if __name__ == "__main__":
    s = HouseNotify()
    d = []
    for i in range(4):
        map = {}
        map["s"] = i
        d.append(map)
    d.sort(key=lambda x:x["s"])
    print(d)